package handler

import (
	"../db"
	"../model"
	"../utils"
	"encoding/json"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"io/ioutil"
	"net/http"
)

func Login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var u model.User
	result, _ := ioutil.ReadAll(r.Body)
	r.Body.Close()
	json.Unmarshal([]byte(result), &u)

	var err error
	var b []byte
	if u.Valid(u.Email, u.Password) {
		response := Response{}.Default()
		response.Body["username"] = "elone"
		response.Body["id"] = u.ID
		response.Token = utils.SetJWTToken(u.ID)
		b, err = json.Marshal(response)

		//保存session
		err := db.SessionManager{}.Set(utils.Uint2Str(u.ID), response.Token)
		if err != nil {
			fmt.Printf("errors :", err)
		}

	} else {
		b, err = json.Marshal(&Response{
			http.StatusForbidden,
			StatusUnauthorized,
			nil,
			"", //token is empty
			"cann't login   ",
			1,
			1,
		})
	}
	if err != nil {
		fmt.Printf("errors :", err)
	}
	w.Write(b)
}

func Logout(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var err error
	var b []byte
	ctx := r.Context()
	userid := utils.GetUserInfoFromContext(ctx)
	//保存session
	err = db.SessionManager{}.Delete(utils.Uint2Str(userid))
	response := Response{}.Default()
	response.Status = http.StatusUnauthorized
	response.Code = StatusUnauthorized
	response.Message = "need login again!"

	b, err = json.Marshal(response)
	if err != nil {
		fmt.Printf("errors :", err)
	}

	w.Write(b)
}


func Register(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var u model.User
	result, _ := ioutil.ReadAll(r.Body)
	r.Body.Close()
	json.Unmarshal([]byte(result), &u)

	var err error
	var resq []byte
	if u,err = u.Save(); err != nil {
		resq, err = json.Marshal(&Response{
			http.StatusForbidden,
			StatusUnauthorized,
			nil,
			"",
			"cann't create user ",
			1,
			1, // errors
		})
	} else {
		response := Response{}.Default()
		response.Body["username"] = "username"
		response.Token = utils.SetJWTToken(u.ID)
		resq, err = json.Marshal(response)
	}
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	w.Write(resq)

}
